/** @format */

import { resultsModel, TBAPIS } from '../../../sdk'
import { CODE_TYPES } from '../../../errorCode'

/**
 *  doCompleteTask 接口使用
 *
 *  检查兑换积分任务，并扣除积分
 *
 * @export
 * @param {IContext<{ activityId: string; taskType: ITaskType; credits?: number }>} context
 * @param {IControllerInfos} { session }
 * @return {*}
 */
export default async function checkExchangeCreditsTask(
  context: IContext<{ activityId: string; key: ITaskType; credits?: number }>,
  { session }: IControllerInfos
) {
  const { key: taskType, credits } = context.data

  // 不是兑换积分类型不校验
  if (taskType !== 'exchange') return

  if (taskType === 'exchange' && !credits) resultsModel.error(CODE_TYPES.PARAMS_ERROR, '缺少credits字段')

  const myCredits = await TBAPIS.queryCredits(context, session)

  console.log('myCredits', myCredits)

  // 积分不足
  if (myCredits < credits) return resultsModel.error(CODE_TYPES.ERROR_NO_CREDITS)

  // 扣积分
  let result = await TBAPIS.changeCredits(context, {
    quantity: +credits,
    change_type: 2, //变更类型：0交易，1：互动活动，2：权益兑换，3：手工调整
    opt_type: 1, // 操作类型，'0'：增加，1：扣减
    remark: `积分兑换任务减积分`
  })

  if (!result) return resultsModel.error(CODE_TYPES.SYSTEM_ERROR)
}
